package ecnu.ecgbackend.controller;

import ecnu.ecgbackend.config.redis.RedisService;
import ecnu.ecgbackend.utils.JwtUtils;
import ecnu.ecgbackend.utils.Result;
import ecnu.ecgbackend.vo.TokenVo;
import io.jsonwebtoken.Jwts;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/sysUser")
public class DiagnosisSysUserController {
    @Resource
    private RedisService redisService;
    @Resource
    private JwtUtils jwtUtils;
    @PostMapping("/refreshToken")
    public Result  refreshToken(HttpServletRequest request){
        String token=request.getHeader("token");
        if(ObjectUtils.isEmpty(token)){
            token=request.getParameter("token");
        }
        Authentication authentication= SecurityContextHolder.getContext().getAuthentication();
        UserDetails details=(UserDetails) authentication.getPrincipal();
        String reToken="";
        if(jwtUtils.validateToken(token,details)){
            reToken=jwtUtils.refreshToken(token);
        }
        long expireTime= Jwts.parser().setSigningKey(jwtUtils.getSecret())
                .parseClaimsJws(reToken.replace("jwt_",""))
                .getBody().getExpiration().getTime();
        String oldTokenKey="token_"+token;
        redisService.del(oldTokenKey);
        String newTokenKey="token_"+reToken;
        redisService.set(newTokenKey,reToken,jwtUtils.getExpiration()/1000);
        TokenVo tokenVo=new TokenVo(expireTime,reToken);
        return Result.ok(tokenVo).message("token生成成功");
    }
}
